package cn.hnc.checkapi.service;

import cn.hnc.checkapi.bean.User;
import cn.hnc.checkapi.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserService {
   @Autowired
   private UserRepository userRepository;

   @Transactional
   @Modifying
   public void save(User user) {
      this.userRepository.save(user);
   }

   @Transactional
   public User findFirstByUsername(String username) {
      return this.userRepository.findFirstByUsername(username);
   }

   @Transactional
   public void login(User user) throws Exception {
      User user1 = this.userRepository.findByUsername(user.getUsername());
      if (user1 == null) {
         throw new Exception("用户名错误");
      } else if (!user1.getPassword().equals(user.getPassword())) {
         throw new Exception("密码错误");
      }
   }

   @Transactional
   public void updatePassword(String username, String password, String newPassword) throws Exception {
      User user1 = this.userRepository.findByUsername(username);
      if (user1 == null) {
         throw new Exception("用户名错误");
      } else if (!user1.getPassword().equals(password)) {
         throw new Exception("原密码错误");
      } else if ("".equals(newPassword)) {
         throw new Exception("请输入新密码");
      } else {
         user1.setPassword(newPassword);
         this.userRepository.save(user1);
      }
   }
}
